package com.ihome.android.market2.frag;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
//import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ihome.android.EAApp;
import com.ihome.android.EAFragment;
import com.ihome.android.academy.AlbumAppActivity;
import com.ihome.android.academy.DetailActivity;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.image.ImageLoader;
import com.ihome.android.image.ImageLoaderFactory;
import com.ihome.android.image.impl.DefaultImageLoadHandler;
import com.ihome.android.academy.R;
import com.ihome.android.market2.asynctask.GetSectionContentAppListTask;
import com.ihome.android.market2.asynctask.GetViewAppDetailTask;
import com.ihome.android.market2.info.AppInfo;
import com.ihome.android.market2.view.CategoryAppItem;
import com.ihome.android.market2.view.PageLine;
import com.ihome.android.util.log.LogUtil;
import com.ihome.android.util.log.UserBehaviorLog;
import com.ihome.android.util.log.UserBehaviorLog.NotifyType;
import com.ihome.android.util.log.UserBehaviorLog.UserBehavior;

public class AlbumAppListFragment extends EAFragment implements OnItemClickListener, OnClickListener, OnKeyListener {
	private final String	TAG								= AlbumAppListFragment.class.getSimpleName();
	private View			fragview;

	private ItemAdapter		mAdapter;
	private List<AppInfo>	mListApp;
	private List<AppInfo>	mListAllApp;
	@EAInjectView(id = R.id.album_app_pageline)
	private PageLine		mPageLine;
	@EAInjectView(id = R.id.gv_album_app)
	private GridView		mGridView;
	@EAInjectView(id = R.id.tv_page_pre)
	private TextView		tv_page_pre;
	@EAInjectView(id = R.id.tv_page_next)
	private TextView		tv_page_next;
	@EAInjectView(id = R.id.album_app_titleline)
	private RelativeLayout	category_line;
	@EAInjectView(id = R.id.album_app_ownedtitle)
	private TextView		appCollectionName;
	@EAInjectView(id = R.id.ll_data_tip)
	private RelativeLayout ll_data_tip;

	/** 该分类当前页数 */
	private int				mCurPage						= 1;
	/** 该分类APP总数 */
	private int				mAppNum							= 0;
	/** 每页展示的APP数量 */
	private final int		APPNUM_PER_PAGE					= 9;

	private final int		MSG_SPINEER_APP_LIST_REFRESH	= 3;
	private final int		MSG_SHOW_PREVIEW_PAGE			= 6;
	private final int		MSG_SHOW_NEXT_PAGE				= 8;

	private Handler			mHandler;

	private ImageLoader		imageLoader;

	private void procHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_SPINEER_APP_LIST_REFRESH:
					mCurPage = 1;
					getAppList();
					break;
				case MSG_SHOW_NEXT_PAGE:
					LogUtil.v(TAG, " ------ MSG_SHOW_NEXT_PAGE ------");
					if (mCurPage * APPNUM_PER_PAGE < mAppNum) {
						mCurPage++;
						int startIndex = (mCurPage - 1) * APPNUM_PER_PAGE;
						if((mCurPage * APPNUM_PER_PAGE) < mAppNum ){
							listCopy(mListAllApp,mListApp, startIndex, APPNUM_PER_PAGE);
						}else{
							listCopy(mListAllApp,mListApp,startIndex,mAppNum - startIndex);
						}

						mAdapter.notifyDataSetChanged();
						focusView();
						setPageLine();
					}
					break;
				case MSG_SHOW_PREVIEW_PAGE:
					LogUtil.v(TAG, " ------ MSG_SHOW_PREVIEW_PAGE ------");
					if (mCurPage > 1) {
						mCurPage--;
						listCopy(mListAllApp,mListApp,(mCurPage-1)*APPNUM_PER_PAGE,APPNUM_PER_PAGE);
						mAdapter.notifyDataSetChanged();
						focusView();
						setPageLine();
					}
					break;
				default:
					break;
				}
			}
		};
	}

	@Override
	protected void setFragView() {
		mFragView = fragview;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		LogUtil.i(TAG, "--> onAttach");
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		procHandler();

		imageLoader = ImageLoaderFactory.create(getActivity());
		((DefaultImageLoadHandler) imageLoader.getImageLoadHandler()).setLoadingResources(R.drawable.icon_default);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		LogUtil.i(TAG, " -->  onCreateView()");
		fragview = (RelativeLayout) inflater.inflate(R.layout.frag_album_applist, container, false);

		return fragview;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		init();
	}

	@Override
	public void onResume() {
		super.onResume();
		LogUtil.d(TAG, " --> onResume() ");
		//focusView();
	}

	@Override
	public void setArguments(Bundle args) {
		super.setArguments(args);
		LogUtil.i(TAG, " -->  setArguments()");
	}

	public void initData() {
		appCollectionName.setText(getActivity().getIntent().getStringExtra(AlbumAppActivity.APP_COLLECTION_NAME));
		if (mListApp == null || mListApp.size() == 0) {
			getAppList();
		}
		else {
			focusView();
		}

		mAdapter.notifyDataSetChanged();
		//setPageLine();
	}

	public void focusView() {
		mGridView.requestFocus();
	}

	private void init() {
		LogUtil.i(TAG, " -->  init()");
		mAdapter = new ItemAdapter(getActivity());
		mGridView.setAdapter(mAdapter);
		mGridView.setFocusable(true);
		mGridView.setOnItemClickListener(this);
		mGridView.setOnKeyListener(this);
		
		tv_page_pre.setOnClickListener(this);
		tv_page_next.setOnClickListener(this);

		initData();
	}

	/**
	 * 设置页数和APP总数
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void setPageLine() {
		mPageLine.setVisibility(View.VISIBLE);
		mPageLine.setPageNum(mCurPage, mAppNum, APPNUM_PER_PAGE, false);
		
		if (mCurPage * APPNUM_PER_PAGE < mAppNum) {
			tv_page_next.setVisibility(View.VISIBLE);
		}

		if (mCurPage * APPNUM_PER_PAGE >= mAppNum) {
			tv_page_next.setVisibility(View.GONE);
			mGridView.requestFocus();
		}

		if (mCurPage == 1) {
			tv_page_pre.setVisibility(View.GONE);
			mGridView.requestFocus();
		}

		if (mCurPage > 1) {
			tv_page_pre.setVisibility(View.VISIBLE);
		}
	}

	private void getAppList() {
		mCurPage = 1;
		mAppNum = 0;
		if (mListApp == null){
			mListApp = new ArrayList<AppInfo>();
		}
		if (mListAllApp == null){
			mListAllApp = new ArrayList<AppInfo>();
		}
		mListApp.clear();
		mListAllApp.clear();

		new GetSectionContentAppListTask(getActivity(), this).execute(getArguments());
	}

	class ItemAdapter extends BaseAdapter {
		private LayoutInflater	mInflater;
		private Context			context;
		private View			view;

		public ItemAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			this.context = context;

		}

		@Override
		public int getCount() {
			int i = 0;
			if (mListApp != null && mListApp.size() > 0) {
				i = mListApp.size();
			}

			if (i < 0)
				i = 0;

			if (i > APPNUM_PER_PAGE)
				i = APPNUM_PER_PAGE;

			return i;
		}

		@Override
		public Object getItem(int position) {
			if (mListApp == null)
				return null;
			return mListApp.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		};

		public void requestFocus() {
			if (view != null) {
				view.requestFocus();
			}
			else {
				LogUtil.e(TAG, "requestFocus() view is NULL ");
			}
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			CategoryAppItem appItem;

			final AppInfo appInfo = (AppInfo) getItem(position);

			if (null == convertView) {
				appItem = new CategoryAppItem(context, imageLoader);
				convertView = appItem.getView();
				convertView.setTag(appItem);
			}
			else {
				appItem = (CategoryAppItem) convertView.getTag();
			}

			appItem.initView(appInfo);
			appItem.setOnKeyListener(AlbumAppListFragment.this);

			appItem.setClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					
					Bundle b = new Bundle();
					b.putInt(HttpKeys.KEY_APPID, Integer.parseInt(appInfo.getAppId()));
					b.putString(HttpKeys.KEY_PATHID, "");
					new GetViewAppDetailTask(AlbumAppListFragment.this.getActivity(),AlbumAppListFragment.this,Integer.parseInt(appInfo.getAppId())).execute(b);
					/** 用户行为统计 详情页“猜你喜欢”点击行为 */
					String[] msg1 = { "", "", "" + appInfo.getAppId(), "", "", "" };
					UserBehaviorLog.getInstance().writeLog(UserBehavior.CLICK_ALBUM_APP, NotifyType.TYPE_NORMAL, "", msg1);
				}
			});

			if (position == 0) {
				view = convertView;
			}

			return convertView;
		}
	}
	
	
	public void toDetailPage(int appId){
		Intent intent = new Intent();
		intent.putExtra(HttpKeys.KEY_APPID, appId);
		intent.setClass(getActivity(), DetailActivity.class);
		getActivity().startActivity(intent);
	}

	/**
	 * 成功获取应用列表回调方法
	 * 
	 * @param mAppList
	 * @param appsNum
	 */
	public void getAppSuccess(List<AppInfo> mAppList, int appsNum) {
		mAppNum = appsNum;
		mListAllApp = mAppList;
		if(mListAllApp.size()>0){
			ll_data_tip.setVisibility(View.GONE);
		}else{
			ll_data_tip.setVisibility(View.VISIBLE);
		}
		if(mAppNum <= APPNUM_PER_PAGE){
			mListApp = mListAllApp;
		}else{
			listCopy(mListAllApp,mListApp,0,APPNUM_PER_PAGE);
		}
		mAdapter.notifyDataSetChanged();
		focusView();
		setPageLine();
	}

	private void listCopy(List<AppInfo> src,List<AppInfo> dst,int start,int num){
		dst.clear();
		for(int i=0,j=start; i< num; i++,j++){
			dst.add(src.get(j));
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		AppInfo info = (AppInfo) arg0.getItemAtPosition(arg2);
		Bundle b = new Bundle();
		b.putInt(HttpKeys.KEY_APPID, Integer.parseInt(info.getAppId()));
		b.putString(HttpKeys.KEY_PATHID, "");
		new GetViewAppDetailTask(AlbumAppListFragment.this.getActivity(),AlbumAppListFragment.this,Integer.parseInt(info.getAppId())).execute(b);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.tv_page_pre:
			mHandler.sendEmptyMessage(MSG_SHOW_PREVIEW_PAGE);
			break;
		case R.id.tv_page_next:
			mHandler.sendEmptyMessage(MSG_SHOW_NEXT_PAGE);
			break;
		default:
			break;
		}

	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		LogUtil.v(TAG, " --> onKey() keyCode = " + keyCode);

		if (keyCode == 92 && event.getAction() == KeyEvent.ACTION_DOWN) {
			mHandler.sendEmptyMessage(MSG_SHOW_PREVIEW_PAGE);
			return true;
		}
		else if (keyCode == 93 && event.getAction() == KeyEvent.ACTION_DOWN) {
			mHandler.sendEmptyMessage(MSG_SHOW_NEXT_PAGE);
			return true;
		}
		return false;
	}

}
